<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
  images: {
    type: Array,
    required: true,
    default: () => [],
  },
})

const currentIndex = ref(0)
let autoPlayTimer = null

// 当前显示内容
const currentContent = computed(() => {
  return props.images[currentIndex.value]?.content || ''
})

// 切换幻灯片
const switchSlide = (index) => {
  currentIndex.value = index
  resetTimer()
}

// 自动播放
const startTimer = () => {
  autoPlayTimer = setInterval(() => {
    currentIndex.value = (currentIndex.value + 1) % props.images.length
  }, 5000)
}

// 重置定时器
const resetTimer = () => {
  clearInterval(autoPlayTimer)
  startTimer()
}

onMounted(() => {
  startTimer()
})

onBeforeUnmount(() => {
  clearInterval(autoPlayTimer)
})
</script>

<template>
  <div class="carousel-container">
    <!-- 图片显示区域 -->
    <div class="image-wrapper">
      <div
        v-for="(item, index) in images"
        :key="index"
        class="slide"
        :class="{ active: currentIndex === index }"
        :style="{ backgroundImage: `url(${item.image})` }"
      ></div>
    </div>

    <!-- 左下角内容 -->
    <div class="content-info">
      {{ currentContent }}
    </div>

    <!-- 右下角序号导航 -->
    <div class="pagination">
      <button
        v-for="(item, index) in images"
        :key="index"
        :class="{ active: currentIndex === index }"
        @click="switchSlide(index)"
      >
        {{ index + 1 }}
      </button>
    </div>
  </div>
</template>

<style scoped>
.carousel-container {
  position: relative;
  width: 100%;
  height: 400px;
  overflow: hidden;
}

.image-wrapper {
  position: relative;
  height: 100%;
}

.slide {
  background-size: cover;
  background-position: center;
  position: absolute;
  width: 100%;
  height: 400px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
}

.slide.active {
  opacity: 1;
}

.slide img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.content-info {
  position: absolute;
  left: 20px;
  bottom: 20px;
  color: var(--text-color-white);
  font-size: 1.5vw;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

.pagination {
  position: absolute;
  right: 20px;
  bottom: 20px;
  display: flex;
  gap: 8px;
}

.pagination button {
  width: 30px;
  height: 30px;
  border: none;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: all 0.3s ease;
}

.pagination button.active {
  background: rgba(255, 255, 255, 0.9);
  transform: scale(1.1);
}
</style>
